package com.matt.service.impl;

import com.matt.commons.dto.sso.StaffDTO;
import com.matt.domain.Children;
import com.matt.domain.GardenLeaderAdvise;
import com.matt.foundation.query.AdviseQuery;
import com.matt.foundation.utils.annotation.OptsTrace;
import com.matt.foundation.vo.AdviseListVo;
import com.matt.repository.ChildrenRepository;
import com.matt.repository.GardenLeaderAdviseRepository;
import com.matt.repository.base.GardenAdviseChildrenRepository;
import com.matt.service.GardenLeaderService;
import com.matt.service.remoteCall.SsoCallService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;

import javax.transaction.Transactional;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * *******************************
 * Created by Ron.
 * form com.matt
 * on 2017/9/19
 * *******************************
 */
@Service
public class GardenLeaderServiceImpl implements GardenLeaderService{
    @Autowired
    private GardenAdviseChildrenRepository gardenAdviseChildrenRepository;

    @Autowired
    private GardenLeaderAdviseRepository gardenLeaderAdviseRepository;

    @Autowired
    private ChildrenRepository childrenRepository;

    @Autowired
    private SsoCallService ssoCallService;

    @Override
    public Page<AdviseListVo> getAdviseList(AdviseQuery query) {

        List<Object[]> objects = gardenAdviseChildrenRepository.findChildrenByAreaId(query);
        Long count = gardenAdviseChildrenRepository.countChildrenByAreaId(query);
        List<AdviseListVo> list = objects.stream().map(o->AdviseListVo.of(o)).collect(Collectors.toList());
        return new PageImpl<AdviseListVo>(list, PageRequest.of(query.getPageNum(), query.getPageSize()), count);
    }

    @Transactional
    @OptsTrace(code = "0001")
    @Override
    public Boolean addAdvise(StaffDTO staff, String childrenId, String content) {
        GardenLeaderAdvise advise = gardenLeaderAdviseRepository.findByChildrenId(childrenId);
        Children children = childrenRepository.findFirstByIdAndAreaId(childrenId, staff.getAreaId());

        if (Objects.isNull(advise)){
            GardenLeaderAdvise newAdvise = new GardenLeaderAdvise();
            newAdvise.setChildrenId(childrenId);
            newAdvise.setChildrenName(children.getName());
            newAdvise.setLeaderId(staff.getId());
            newAdvise.setLeaderName(staff.getRealName());
            newAdvise.setContent(content);
            gardenLeaderAdviseRepository.save(newAdvise);
        }else {
            advise.setContent(content);
            gardenLeaderAdviseRepository.save(advise);
        }
        return true;
    }
}
